package routing.googleadapter;


import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class GoogleAddressKMLParser {
	private String kmlData;
	private String addressString;
	
	/**
	 * @param xmlKmlData: full XML data
	 */
	public GoogleAddressKMLParser(String xmlKmlData) {
		kmlData = xmlKmlData;
		addressString = null;
	}
	
	public String getAddress() {
		if (addressString == null) parse();
		
		return addressString;
	}
	
	/**
	 * parses the data
	 */
	
	private void parse() {		
		DocumentBuilder dBuilder;
		Document document;
		
		try {
			dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			document = dBuilder.parse(new InputSource(new StringReader(kmlData)));
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}

		NodeList nodes = document.getElementsByTagName("result");
		for (int i = 0; i < nodes.getLength(); i++) {
			Node item = nodes.item(i);
			Node n = null;
			NodeList subNodes = item.getChildNodes();
			boolean streetAddressFound = false;

			for (int j = 0; j < subNodes.getLength(); j++) {
				n = subNodes.item(j);
				if (n.getNodeName().equals("type") && n.getFirstChild().getNodeValue().equals("street_address")) {
					streetAddressFound = true;
					break;
				}
			}

			if (streetAddressFound) {
				n = n.getNextSibling();
				
				while (!n.getNodeName().equals("formatted_address")) n = n.getNextSibling();
				
				addressString = n.getFirstChild().getNodeValue();				
			}
		}
	}
}